package com.example.util.util;

import com.google.common.collect.Lists;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;

import java.io.*;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

/**
 * 创建文件夹
 * 
 * @author 王超
 *
 */
public class FileFolder {
	private static final Logger logger = LoggerFactory.getLogger( FileFolder.class );


	/**
	 * @Title: write
	 * @Description: 将内容写入指定目录
	 * @author: huzhenxing
	 * @param path 目标文件路径
	 * @param content 写入文本
	 * @param append 是否追加，true追加，false覆盖
	 * @throws IOException
	 */
	public static void write( String path, String content, boolean append ) throws IOException {
		FileUtils.writeStringToFile( new File( path ), content, append );
	}

	/**
	 * @Description 向文件服务器写入；文件服务器中如果根目录不存在，则不创建；抛出异常。
	 * @author:suyutang
	 * @param :[rootPath, willBuildPath, content, append]
	 * @return void
	 * @Date:11:23 2019/6/20
	 */
	public static void writeToFileServer( String rootPath, String willBuildPath,String content, boolean append ) throws IOException {
        File file = new File(rootPath);
        if(file.exists()){
            FileUtils.writeStringToFile( new File( rootPath+willBuildPath), content, append );
        }else{
            throw new IOException("文件服务器的根目录不存在:"+rootPath);
        }
	}

	/**
	 * 功能：从txt文本中读入指定范围的行
	 * 
	 * @param :path 代表文件的路径
	 * @param begin 开始行
	 * @param end 结束行
	 * @return List<String>
	 * @throws IOException
	 */
	public static List<String> readLines( String fileName, int begin, int end ) {
		List<String> lines = Lists.newArrayList( );
		if( begin == end ) {
			return lines;
		} else if( begin > end ) {
			int tmp = begin;
			begin = end;
			end = tmp;
		}
		Path path = Paths.get( fileName );
		try {
			if( Files.exists( path, LinkOption.NOFOLLOW_LINKS ) ) {
				if( !path.toString( ).endsWith( ".txt" ) )
					return lines;
				BufferedReader read = null;
				try {
					read = new BufferedReader( new FileReader( path.toFile( ) ) );
					String read2 = null;
					int i = 0;
					while( ( read2 = read.readLine( ) ) != null ) {
						i++;
						if( i > begin && i <= end ) {
							lines.add( read2 );
						} else if(i>end){
							break;
						}
					}
					return lines;
				} catch( Exception e ) {
					logger.error( "读取文件失败{}", path.toString( ) );
				} finally {
					try {
						read.close( );
					} catch( Exception e ) {
						read = null;
					}
				}
			} else {
				return Lists.newArrayList( );
			}
		} catch( Exception e ) {
			logger.error( "读取文件失败，请检查文件{}", path.toString( ) );
		}
		return Lists.newArrayList( );
	}

	public static List<String> readLines3( String fileName, int begin, int end ) {
		List<String> lines = Lists.newArrayList( );
		if( begin == end ) {
			return lines;
		} else if( begin > end ) {
			int tmp = begin;
			begin = end;
			end = tmp;
		}

		File file = null;
		try {
			file = new File( fileName );
		} catch( NullPointerException e ) {
			return lines;
		}

		try {
			if( file.exists( ) ) {
				try( FileReader fr = new FileReader( file ); BufferedReader br = new BufferedReader( fr ); LineNumberReader lr = new LineNumberReader( br ) ) {
					lr.setLineNumber( begin );
					try {
						String line = lr.readLine( );
						int index = begin;
						while( line != null && index <= end ) {
							lines.add( line );
							line = lr.readLine( );
							index++;
						}
					} catch( IOException e ) {
						return Lists.newArrayList( );
					}
				}
			} else {
				return Lists.newArrayList( );
			}
		} catch( Exception e ) {
			return Lists.newArrayList( );
		}
		return lines;

	}

	public static List<String> readFileAsList(String path) {
		Assert.notNull(path, "path can not be null");
		List<String> list = null;
		try {
			list = Files.readAllLines(Paths.get(path), Charset.forName("utf-8"));
		} catch (IOException e) {
			logger.error(e.getMessage(), e);
			throw new RuntimeException(e);
		}
		return list;
	}
}
